//
//  LoginViewModel.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/6/4.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa

let minPasswordLength = 6

class LoginViewModel {
    var validatedUsername: Observable<ValidationResult>!
    var validatedPassword: Observable<ValidationResult>!
    
    var signinEnable: Observable<Bool>!
    var signIn: Observable<Bool>!
    
    init(username: Observable<String>, password: Observable<String>, loginTaps: Observable<Void>) {
        
        validatedUsername = username
            .map { strUsername in
                let numCount = strUsername.count
                if numCount == 0 {
                    return ValidationResult.empty
                }
                if !strUsername.isMobile {
                    return ValidationResult.failed(message: "请输入正确的手机号")
                }
                return ValidationResult.ok(message: "")
            }.share(replay:1)
        
        validatedPassword = password
            .map{ strPassword in
                let numCount = strPassword.count
                if numCount == 0 {
                    return ValidationResult.empty
                }
                if numCount < minPasswordLength {
                    return ValidationResult.failed(message: "密码至少需要\(minPasswordLength)位")
                }
                return ValidationResult.ok(message: "")
            }.share(replay:1)
        
        signinEnable = Observable.combineLatest(validatedUsername, validatedPassword) {
            tu, tp in
                return tu.isValid && tp.isValid
            }.distinctUntilChanged().share(replay:1)
        
        let usernameAndPassword = Observable.combineLatest(username, password) { (username:$0, password:$1) }.share(replay: 1)
        signIn = loginTaps.withLatestFrom(usernameAndPassword)
            .flatMapLatest { pair -> Observable<Bool> in
                SVProgressHUD.show()
                return NetworkTool
                    .requestData(url: ActionURL.LOGIN, param: ["mobile":pair.username,"password":pair.password])
                    .map({ (json) -> Bool in
                        MainTools.shared.userModel = UserModel.mj_object(withKeyValues: json["rows"].dictionaryObject)
                        MainTools.makeToast(message: json["message"].stringValue)
                        return true
                    })
                    .catchErrorJustReturn(false)
                    .observeOn(MainScheduler.instance)
            }.share(replay: 1)
    }
    
}

extension Reactive where Base: UILabel {
    var validationResult: Binder<ValidationResult> {
        return Binder(base) { label, result in
            label.textColor = result.textColor
            label.text = result.description
        }
    }
}

enum ValidationResult: CustomStringConvertible {
    case ok(message: String)
    case empty
    case validating
    case failed(message: String)
    
    var textColor: UIColor {
        switch self {
        case .ok:
            return UIColor.green
        case .empty:
            return UIColor.white
        case .validating:
            return UIColor.white
        case .failed:
            return UIColor.red
        }
    }
    
    var description: String {
        switch self {
        case let .ok(message):
            return message
        case .empty:
            return ""
        case .validating:
            return "validating ..."
        case let .failed(message):
            return message
        }
    }
    
    var isValid: Bool {
        switch self {
        case .ok:
            return true
        default:
            return false
        }
    }
}
